package com.haois.mp.database.module.miniapp.rest;


import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.google.gson.Gson;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.exception.ErrorException;
import com.haois.mp.database.module.remote.service.IUserService;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.haois.mp.database.module.basic.controller.BaseController;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.util.jx.DateUtil;
import com.haois.mp.database.util.mp.HandleToken;
import com.haois.mp.database.util.mp.ProduceJwt;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mini/rest/user")
public class UserMiniController extends BaseController {

    private static final Logger logger = LoggerFactory
            .getLogger(UserMiniController.class);

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserTokenService iUserTokenService;

    ProduceJwt produceJwt = new ProduceJwt();
    private Gson gson = new Gson();


    @RequestMapping("/getInfo")
    public Map getInfo(HttpServletRequest request, String memberNum, String oid)
            throws RuntimeException, WxErrorException, ErrorException {
        String access_token = (String) request.getAttribute("access_token");
        if (StringUtils.isNotBlank(memberNum)) {
            Map userInfo = iUserService.getUserInfo(access_token, memberNum, oid);
            return userInfo;
        } else {
            Map userInfo = iUserService.getUserInfo(access_token);
            return userInfo;
        }
    }


    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    public Map updateInfo(String name, String wechat, String email, String birthday, String introduce, String sex,
                          String addr, String mobiles, String tel, HttpServletRequest request) throws
            RuntimeException, WxErrorException, ErrorException {
        Map params = new HashMap();
        params.put("name", name);
        params.put("weChat", wechat);
        params.put("email", email);
        params.put("birthday", birthday);
        params.put("introduce", introduce);
        params.put("site", addr);
        params.put("mobiles", mobiles);
        params.put("tel", tel);
        String access_token = (String) request.getAttribute("access_token");
        Map map = iUserService.updateUserInfo(params, access_token);
        return map;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map loginAsync(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password,
            @RequestParam(value = "wxCode", required = true) String wxCode, WxMaUserInfo userInfo,
            HttpServletRequest request) throws RuntimeException, WxErrorException {
        userInfo = userInfo == null ? new WxMaUserInfo() : userInfo;
        Map result = new HashMap();
        WxMaJscode2SessionResult wResult = wxMaUserService.getSessionInfo(wxCode);
        if (wResult != null) {
            result = iUserService.login(username, password, wResult.getOpenid(), MpTypeEnum.MINIAPP.getType(), wResult.getSessionKey());
            String openId = wResult.getOpenid();
            if ("00".equals(result.get("code")) || "05".equals(result.get("code"))) {
                UserToken userToken = iUserTokenService.findByOpenId(wResult.getOpenid(), MpTypeEnum.MINIAPP.getType());
                String access_token = (String) result.get("data");
                UserToken oldUt = iUserTokenService.findByUserId(username, MpTypeEnum.MINIAPP.getType());
                if (oldUt != null && !oldUt.getOpenId().equals(openId)) {
                    iUserTokenService.logout(oldUt.getOpenId(), MpTypeEnum.MINIAPP.getType(), "绑定微信用户[" + openId + "]");
                }
                if (userToken != null) {
                    iUserTokenService.saveUserTokenHis(userToken, "重新登录", MpTypeEnum.MINIAPP.getType());
                    userToken.setUpdateTime(DateUtil.getYMdHm());
                    userToken.setUserId(username);
                    userToken.setAccessToken(access_token);
                    iUserTokenService.updateInfo(userToken, userInfo);
                } else {
                    userToken = new UserToken(username, openId, access_token);
                    userToken.setCreateTime(DateUtil.getYMdHm());
                    userToken.setSessionKey(wResult.getSessionKey());
                    iUserTokenService.login(userToken, userInfo);
                }
                result.put("code", "00");
                result.put("msg", "登录成功");
                result.put("data", userToken);
            }
        } else {
            result.put("code", "10");
            result.put("msg", "小程序授权失败");
        }
        return result;

    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public Map logout(HttpServletRequest request)
            throws WxErrorException {
        String access_token = (String) request.getAttribute("access_token");
        UserToken userToken = iUserTokenService.findByAccessToken(access_token, MpTypeEnum.MINIAPP.getType());
        Map result = new HashMap();
        if (userToken != null) {
            iUserTokenService.logout(userToken.getOpenId(), MpTypeEnum.MINIAPP.getType(), null);
        }
        result.put("code", "00");
        result.put("msg", "退出成功");
        return result;
    }

    /**
     * 修改密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param request
     * @return
     * @throws RuntimeException
     */
    @RequestMapping(value = "/updatePSW", method = RequestMethod.POST)
    public Map updatePSW(
            @RequestParam(value = "oldPassword") String oldPassword,
            @RequestParam(value = "newPassword") String newPassword,
            HttpServletRequest request)
            throws RuntimeException, WxErrorException {
        String access_token = (String) request.getAttribute("access_token");
        Map map = iUserService.modifyPwd(oldPassword, newPassword, access_token);
        return map;

    }

    /**
     * 修改头像
     *
     * @param request
     * @param media_id 微信上传的头像地址
     * @return
     */
    @RequestMapping(value = "/userPhoto", method = RequestMethod.POST)
    public Map updateUserPhoto(HttpServletRequest request, String media_id) throws WxErrorException {
        try {
            logger.info("上传到微信的图片地址为:[{}]", media_id);
            File file = null;
            //wxMpMaterialService.mediaDownload(media_id);
            String access_token = (String) request.getAttribute("access_token");
            Map map = iUserService.modifyPhoto(file, access_token);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            Map errMap = new HashMap();
            errMap.put("respCode", "01");
            errMap.put("msg", "上传头像异常,请稍后再试");
            return errMap;
        }
    }


    /**
     * 重置密码
     *
     * @param phoneNumber 电话
     * @param code        验证码
     * @param newPassword 新的密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/reset/password", method = RequestMethod.POST)
    public Map forgetPSW(@RequestParam("phoneNumber") String phoneNumber,
                         @RequestParam("code") String code,
                         @RequestParam("newPassword") String newPassword, HttpServletRequest request) throws WxErrorException {
        String access_token = (String) request.getAttribute("access_token");

        Map result = iUserService.resetUserPassword(access_token, code, newPassword, phoneNumber);
        return result;

    }

    /**
     * 退出登录
     */
    @RequestMapping("/state")
    public Map getState(HttpServletRequest request, String openId,
                        @RequestParam(value = "wxCode", required = true) String wxCode)
            throws WxErrorException {
        WxMaJscode2SessionResult wResult = wxMaUserService.getSessionInfo(wxCode);
        if (wResult != null) {
            openId = wResult.getOpenid();
        }
        HandleToken handleToken = new HandleToken();
        UserToken userToken = iUserTokenService.findByOpenId(openId, MpTypeEnum.MINIAPP.getType());
        Map result = new HashMap();
        result.put("code", "10");
        result.put("msg", "未登录");
        if (userToken != null) {
            try {
                handleToken.parseJWT(userToken.getAccessToken());
                result.put("code", "00");
                result.put("msg", "登录状态");
                result.put("data", userToken);
            } catch (Exception e) {
                iUserTokenService.logout(userToken.getOpenId(), MpTypeEnum.MINIAPP.getType(), e.getMessage());
            }
        }
        return result;
    }
}
